#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;

class Solution{
    private:
    int num = 0;

    public:
    int ans1(int n) {
        vector<vector<string>> solutions;
        vector<int> queens(n, -1);
        unordered_set<int> columns;
        unordered_set<int>diagonals1;
        unordered_set<int>diagonals2;
        backtrack(queens, n, 0, columns, diagonals1, diagonals2);
        return num;
    }

    void backtrack(vector<int> &queens, int n, int row, unordered_set<int> &columns, unordered_set<int> &diagonals1, unordered_set<int> &diagonals2) {
        if (row == n) {
            num++;
        } else {
            for (int i = 0; i < n; i++) {
                if (columns.find(i) != columns.end()) {
                    continue;
                }
                int diagonal1 = row - i;
                if (diagonals1.find(diagonal1) != diagonals1.end()) {
                    continue;
                }
                int diagonal2 = row + i;
                if (diagonals2.find(diagonal2) != diagonals2.end()) {
                    continue;
                }
                queens[row] = i;
                columns.insert(i);
                diagonals1.insert(diagonal1);
                diagonals2.insert(diagonal2);
                backtrack(queens, n, row + 1, columns, diagonals1, diagonals2);
                queens[row] = -1;
                columns.erase(i);
                diagonals1.erase(diagonal1);
                diagonals2.erase(diagonal2);
            }
        }
    }

};

void test(){
    Solution s;
    int n = 4;
    int ret = s.ans1(n);

    cout << ret << endl;
}

int main(void){
    test();

    return 0;
}